package com.mall.db.api;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.commons.utils.PageResult;
import com.mall.db.mapper.PmsProductCategoryMapper;
import com.mall.domain.PmsProductCategory;
import com.mall.interface1.api.PmsProductCategoryApi;
import com.mall.vo.PmsProductCategoryVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class PmsProductCategoryApiImpl implements PmsProductCategoryApi {

    @Autowired
    private PmsProductCategoryMapper categoryMapper;

    //查询所有一级分类及子分类
    @Override
    public List<PmsProductCategoryVo> findAll() {
        LambdaQueryWrapper<PmsProductCategory> qw = new LambdaQueryWrapper<>();

        List<PmsProductCategory> pmsProductCategories = categoryMapper.selectList(qw);

        List<PmsProductCategoryVo> voList = pmsProductCategories.stream().map(pmsProductCategory -> {
            qw.eq(PmsProductCategory::getParentId, pmsProductCategory.getId());
            List<PmsProductCategory> selectList = categoryMapper.selectList(qw);

            PmsProductCategoryVo vo = new PmsProductCategoryVo();
            BeanUtil.copyProperties(pmsProductCategory, vo);
            vo.setChildren(selectList);
            return vo;
        }).collect(Collectors.toList());

        return voList;
    }

    @Override
    public Long add(PmsProductCategory pmsProductCategory) {
        categoryMapper.insert(pmsProductCategory);
        return pmsProductCategory.getId();
    }

    //删除商品
    @Override
    public void deleteById(Long id) {
        categoryMapper.deleteById(id);
    }

    //分页查询商品分类
    @Override
    public PageResult listParentId(Integer pageNum, Integer pageSize, Long parentId) {
        Page<PmsProductCategory> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<PmsProductCategory> qw = new LambdaQueryWrapper<>();
        qw.eq(PmsProductCategory::getParentId,parentId);

        Page<PmsProductCategory> pmsProductCategoryPage = categoryMapper.selectPage(page, qw);
        return new PageResult(pageNum,pageSize, (int) pmsProductCategoryPage.getTotal(),pmsProductCategoryPage.getRecords());
    }

    //根据id获取商品分类
    @Override
    public PmsProductCategory findById(Long id) {
        return categoryMapper.selectById(id);

    }

    //修改商品分类
    @Override
    public void updateById(PmsProductCategory pmsProductCategory) {
        categoryMapper.updateById(pmsProductCategory);

    }
}
